package qingxin.servlet.client.information;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.InformationDAO;
import qingxin.dao.PhotoDAO;
import qingxin.factory.DAOFactory;
import qingxin.vo.Information;

@WebServlet("/client/information/getAll")
public class GetAllServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private InformationDAO informationDAO;
	private PhotoDAO photoDAO;
	
	public GetAllServlet(){
		super();
		informationDAO = DAOFactory.getInformationDAO();
		photoDAO = DAOFactory.getPhotoDAO();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		    throws ServletException, IOException {
				request.setCharacterEncoding("UTF-8");
		    	response.setContentType("text/html; charset=utf-8");
		    	response.setCharacterEncoding("utf-8");
				PrintWriter writer = response.getWriter();
				
				try{
					String limitS = request.getParameter("limit");
					int limit = (limitS == null) ? 20 : Integer.parseInt(limitS);
					String startS = request.getParameter("start");
					int start = (startS == null) ? Integer.MAX_VALUE : Integer.parseInt(startS);
					
					JSONObject jsonResult = new JSONObject();
					JSONArray jsonInformations = new JSONArray();
					Information[] informations = informationDAO.getAll(limit, start);
					for(Information information : informations){
						JSONObject jsonInformation = new JSONObject();
						jsonInformation.put("id", information.getInformationID());
						jsonInformation.put("title", information.getTitle());
						jsonInformation.put("content", information.getContent());
						jsonInformation.put("original_addr", photoDAO.getByID(information.getPhotoID()).getOriginalAddress());
						jsonInformations.put(jsonInformation);
					}
					
					jsonResult.put("information", jsonInformations);
					writer.println(jsonResult.toString());
					
					response.setStatus(HttpServletResponse.SC_OK);
				}
				catch(Exception e){
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					writer.println("{\"msg\":\"wrong\"}");
				}
				finally{
					writer.flush();
					writer.close();
				}
			}
}
